package com.itheima.mm.controller;

import com.itheima.mm.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.util.ClassUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author ：seanyang
 * @date ：Created in 2019/8/17
 * @description ：公共控制器
 * @version: 1.0
 */
@Slf4j
@WebServlet("/common/*")
public class CommonController extends BaseController {

    public void upload(MultipartHttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 通过request对象getFileMap()，获取到MultipartFile集合
        Map<String, MultipartFile> fileMap = request.getFileMap();
// 把上传成功的文件相对路径，返回给客户端
        List<Map<String, String>> resultList = new ArrayList<>();
// 遍历MultipartFile集合，每个MultipartFile就是一个文件附件
        Iterator<String> iterator = request.getFileNames();
        while (iterator.hasNext()) {
            // 处理每个MultipartFile
            while (iterator.hasNext()) {
                String fileName = iterator.next();
                MultipartFile multipartFile = request.getFile(fileName);
                log.debug("fileName-{}:{}-{}-{}", fileName, multipartFile.getOriginalFilename(), multipartFile.getName(), multipartFile.getSize());
                // 对文件名进行重命名,UUID+文件后缀(文件类型)
                String newFileName = UUID.randomUUID().toString().replace("-", "");
                String fileType = fileName.substring(fileName.lastIndexOf('.'));
                fileName = newFileName + fileType;
                String contexPath = ClassUtils.getDefaultClassLoader().getResource("public").getPath();
                log.info("contexPath:{}", contexPath);
                // 读取配置文件,获得上传图片的相对路径
                ResourceBundle resourceBundle = ResourceBundle.getBundle("app-config");
                String uploadDirPath = resourceBundle.getString("upload_path");
                // 读取文件数据，并保存到Web资源目录
                File uploadDir = new File(contexPath, uploadDirPath);
                // 构建本地存储的文件对象
                File uploadFile = new File(uploadDir, fileName);
                // 从上传文件项获取字节输入流，然后保存到指定的上传目录下
                InputStream inputStream = multipartFile.getInputStream();
                FileOutputStream fos = new FileOutputStream(uploadFile);
                // 通过IO工具存入磁盘
                IOUtils.copy(inputStream, fos);
                // 关闭流
                IOUtils.closeQuietly(fos);
                IOUtils.closeQuietly(inputStream);
                // 存入数据库的路径
                String saveDbPath = uploadFile.getAbsolutePath().replace(new File(contexPath).getAbsolutePath(), "");
                Map mapResult = new HashMap();
                // 以上传的文件组件名为key,数据库保存的相对路径为value
                mapResult.put(fileName, saveDbPath);
                resultList.add(mapResult);
            }
        }
    }
}